package com.itzmn.newcode.offer;

import java.util.ArrayList;

/**
 * @Author: 张梦楠
 * @Date: 2018/11/13 17:33
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description:
 *
 *  思路：
 *   打印一圈，那么左上方的坐标和右下方的坐标有规律，两个必须是在行数和列数不能超过。
 */
public class PrintMatrix {

    public static void main(String[] args) {


        new PrintMatrix().init();

    }

    public void init(){

        int[][] ints = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
        ArrayList<Integer> integers = printMatrix(ints);
        System.out.println(integers);
    }

    public ArrayList<Integer> printMatrix(int [][] matrix) {

        // 记录开始的行列，记住右下角的行列，比较这两个是否是相减等于0，等于就不打印，不等于就继续
        ArrayList<Integer> integers = new ArrayList<>();


        int row = 0;
        int col = 0;

        int r_row=matrix.length-1;
        int r_col=matrix[0].length-1;

        while (r_col-col-col>=0 && r_row-row-row>=0){

            if (r_row-row-row==0){
                for (int i=col;i<=r_col-col;i++){
                    System.out.println(matrix[row][i]);
                    integers.add(matrix[row][i]);
                }
            }
            else if (r_col-col-col==0){
                int temprow = r_row-row;
                for (int i=row;i<=temprow;i++){
                    System.out.println(matrix[i][col]);
                    integers.add(matrix[i][col]);
                }
            }
            else {
                for (int i=col;i<=r_col-col;i++){
                    System.out.println(matrix[row][i]);
                    integers.add(matrix[row][i]);
                }
                int temprow = row+1;
                for (int i= temprow;i<=r_row-row;i++){
                    System.out.println(matrix[i][r_col-col]);
                    integers.add(matrix[i][r_col-col]);
                }
                int tempcol = r_col-col-1;

                for (int i = tempcol;i>=col;i--){
                    System.out.println(matrix[r_row-row][i]);
                    integers.add(matrix[r_row-row][i]);
                }
                temprow = r_row-row-1;
                for (int i=temprow;i>row;i--){
                    System.out.println(matrix[i][col]);
                    integers.add(matrix[i][col]);
                }
            }

            row++;
            col++;
        }


        return integers;
    }

}
